const OSS = require('ali-oss')
const config = {
    ossConfig: {
        region: 'oss-cn-beijing',
        bucket: 'liangpiao-ticket-img',
        accessKeyId: 'LTAI5t7zraWDQjQZPr6DeiEy',
        accessKeySecret: 'k8vXVzOVpqe27I2GY9IISuvkwIomzR'
    }
}

export function readFileAsBuffer(file) {
    const reader = new FileReader()
    return new Promise((resolve, reject) => {
        reader.readAsDataURL(file)
        reader.onload = function (e) {
            const base64File = reader.result.replace(/^data:\w+\/\w+;base64,/, '')
            resolve(new OSS.Buffer(base64File, 'base64'))
        }
    })
}

// 生成唯一onlyId
export function onlyId() {
    const s = []
    const hexDigits = '0123456789abcdef'
    for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
    }
    s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = '-'
    let onlyId = s.join('')
    return onlyId
}

export function upload(file_re, file, type) {
    const client = new OSS({
        region: config.ossConfig.region,
        bucket: config.ossConfig.bucket,
        accessKeyId: config.ossConfig.accessKeyId,
        accessKeySecret: config.ossConfig.accessKeySecret
    })

    if (type == 'images') {
        let size = file.size
        if (size / (1024 * 1024) > 1) {
            notification.error({
                message: '图片错误',
                description: '图片文件大小不能超过1M'
            })
            return
        }
    } else if (type == 'video') {
        let size = file.size
        if (size / (1024 * 1024) > 10) {
            notification.error({
                message: '视频错误',
                description: '视频文件大小不能超过10M'
            })
            return
        }
    }

    let imgType = file.name.substr(file.name.length - 4)
    let store = `/${type}/` + onlyId() + imgType

    return client.put(store, file_re).then(res => {
        return {
            data: res,
            url: res.url
        }
    })
}
